package com.ruoyi.service.impl;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.domain.ApprovalRecord;
import com.ruoyi.domain.ForceTerminationLog;
import com.ruoyi.domain.PurchaseDetailBom;
import com.ruoyi.mapper.*;
import com.ruoyi.service.genericity;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.domain.ErpPurchaseRequestManagement;
import com.ruoyi.service.IErpPurchaseRequestManagementService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 请购单管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-17
 */
@Service
@Transactional
public class ErpPurchaseRequestManagementServiceImpl  extends ServiceImpl<ErpPurchaseRequestManagementMapper,ErpPurchaseRequestManagement>implements IErpPurchaseRequestManagementService {
    @Autowired
    private ErpPurchaseRequestManagementMapper erpPurchaseRequestManagementMapper;
    @Autowired
    private forceTerminationMapper forceTerminationMapper;
    @Autowired
    private ApprovalRecordMapper approvalRecordMapper;
    @Autowired
    private ErpPurchaseRequestPendingDetailMapper erpPurchaseRequestPendingDetailMapper;
    @Autowired
    private PurchaseDetailBomMapper purchaseDetailBomMapper;

    /**
     * 查询请购单管理
     *
     * @param id 请购单管理主键
     * @return 请购单管理
     */
    @Override
    public ErpPurchaseRequestManagement selectErpPurchaseRequestManagementById(String id) {
        return erpPurchaseRequestManagementMapper.selectErpPurchaseRequestManagementById(id);
    }

    /**
     * 查询请购单管理列表
     *
     * @param erpPurchaseRequestManagement 请购单管理
     * @return 请购单管理
     */
    @Override
    public List<ErpPurchaseRequestManagement> selectErpPurchaseRequestManagementList(ErpPurchaseRequestManagement erpPurchaseRequestManagement) {
        return erpPurchaseRequestManagementMapper.selectErpPurchaseRequestManagementList(erpPurchaseRequestManagement);
    }

    /**
     * 新增请购单管理
     *
     * @param erpPurchaseRequestManagement 请购单管理
     * @return 结果
     */


    /**
     * 修改请购单管理
     *
     * @param erpPurchaseRequestManagement 请购单管理
     * @return 结果
     */
    @Override
    public int updateErpPurchaseRequestManagement(ErpPurchaseRequestManagement erpPurchaseRequestManagement) {
        erpPurchaseRequestManagement.setUpdateTime(DateUtils.getNowDate());
        return erpPurchaseRequestManagementMapper.updateErpPurchaseRequestManagement(erpPurchaseRequestManagement);
    }

    /**
     * 批量删除请购单管理
     *
     * @param ids 需要删除的请购单管理主键
     * @return 结果
     */
    @Override
    public int deleteErpPurchaseRequestManagementByIds(String[] ids) {
        return erpPurchaseRequestManagementMapper.deleteErpPurchaseRequestManagementByIds(ids);
    }

    /**
     * 删除请购单管理信息
     *
     * @param id 请购单管理主键
     * @return 结果
     */
    @Override
    public int deleteErpPurchaseRequestManagementById(String id) {
        return erpPurchaseRequestManagementMapper.deleteErpPurchaseRequestManagementById(id);
    }


    @Override
    public Map insertErpPurchaseRequestManagement(ErpPurchaseRequestManagement erpPurchaseRequestManagement) {
        System.out.println("DateUtils.getNowDate() = " + DateUtils.getNowDate());
        Date daohuorq = erpPurchaseRequestManagement.getDaohuorq();
        Date purchaseDate = erpPurchaseRequestManagement.getPurchaseDate();

        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        sdf1.format(daohuorq);
        sdf1.format(purchaseDate);
        System.out.println(sdf1.format(daohuorq));
        System.out.println(sdf1.format(purchaseDate));
        erpPurchaseRequestManagement.setCreateTime(DateUtils.getNowDate());
        int i = erpPurchaseRequestManagementMapper.insertErpPurchaseRequestManagement(erpPurchaseRequestManagement);
        Map<String, String> addMap = new HashMap<>();
        switch (i) {
            case 0:
                addMap.put("审核状态", "0");
            case 1:
                addMap.put("是否保存成功？", "保存失败");
        }
        return addMap;
    }
    @Override
    public Map<String, Integer> updateAudit(ErpPurchaseRequestManagement erpPurchaseRequestManagement) {
        LambdaUpdateWrapper<ErpPurchaseRequestManagement> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(ErpPurchaseRequestManagement::getId, erpPurchaseRequestManagement.getId())
                //审批状态 变为已审批
                /* 订单状态
                 * 1 如果选择未通过 则订单状态变为 已完成
                 * 2 如果选择未 拒绝 则订单状态变为审核驳回*/
                .set(ErpPurchaseRequestManagement::getAuditStatus, 1);
        //选择分为两种 0未拒绝 1为同意

        if (erpPurchaseRequestManagement.getChoice() == 0) {
            lambdaUpdateWrapper.eq(ErpPurchaseRequestManagement::getId, erpPurchaseRequestManagement.getId())
                    .set(ErpPurchaseRequestManagement::getDocStatus, 3).set(ErpPurchaseRequestManagement::getAuditStatus, 3);

//            lambdaUpdateWrapper.eq(ErpPurchaseRequestManagement::getId, erpPurchaseRequestManagement.getId())
//                    .set(ErpPurchaseRequestManagement::getDocStatus, 4).set(ErpPurchaseRequestManagement::getAuditStatus, 2);
            erpPurchaseRequestManagementMapper.update(null, lambdaUpdateWrapper);
        } else if (erpPurchaseRequestManagement.getChoice() == 1) {
            lambdaUpdateWrapper.eq(ErpPurchaseRequestManagement::getId, erpPurchaseRequestManagement.getId())
                    .set(ErpPurchaseRequestManagement::getDocStatus, 2).set(ErpPurchaseRequestManagement::getAuditStatus, 2);
            erpPurchaseRequestManagementMapper.update(null, lambdaUpdateWrapper);
        }

        int update = erpPurchaseRequestManagementMapper.update(null, lambdaUpdateWrapper);
        Map<String, Integer> auditMap = new HashMap<>();
//            设置按钮状态
        if (update > 0) {
            switch (erpPurchaseRequestManagement.getChoice()) {
                //0 代表审核按钮为使用状态  1代表审核按钮为禁用状态 2 代表无效
                case 0 -> auditMap.put("审核状态", 0);
                case 1 -> auditMap.put("审核状态", 1);
                default -> auditMap.put("审核状态", 2);
            }
            ;
            //设置审核状态 0
            auditMap.put("提交成功？", 1);
            //添加审核记录 1已审核
            System.out.println("erpSupplierManagement.getId() = " + erpPurchaseRequestManagement.getId());
            // 获取记录
            ErpPurchaseRequestManagement one = getOne(
                    new LambdaQueryWrapper<ErpPurchaseRequestManagement>()
                            .eq(ErpPurchaseRequestManagement::getId, erpPurchaseRequestManagement.getId()));

            //判断如果one获取到了就 加入到审核记录表
            if (one != null) {
                ApprovalRecord approvalRecord1 = new ApprovalRecord();
                approvalRecord1.setJiId(one.getId());
                //将2 作为 外键 代表请购单的所有记录
                approvalRecord1.setBusinessId(2);
                approvalRecord1.setBusinessType("请购管理");


                approvalRecord1.setCreateTime(one.getUpdateTime());
                approvalRecord1.setUpdateTime(one.getUpdateTime());
                LocalDateTime now = LocalDateTime.now();
                System.out.println("当前时间：" + now); // 输出类似：2025-07-21T15:30:00.123

                // 格式化输出
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String formattedTime = now.format(formatter);
                System.out.println("格式化后：" + formattedTime); // 输出：2025-07-21 15:30:00
                approvalRecord1.setApprovalTime(formattedTime);
                approvalRecord1.setResult(one.getChoice());
                approvalRecord1.setOpinion(erpPurchaseRequestManagement.getOpinion());
                System.err.println("approvalRecord1 = " + approvalRecord1);

                int insert = approvalRecordMapper.insertApprovalRecord(approvalRecord1);
                System.err.println(insert);
            }
            return auditMap;
        } else {
            auditMap.put("审核失败", 0);
            return auditMap;
        }
        // 1. 传入 null 代表不需要依赖于实体对象

    }


    @Override
    public Map<String, Integer> submit(int id) {
        LambdaUpdateWrapper<ErpPurchaseRequestManagement> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();

        lambdaUpdateWrapper.eq(ErpPurchaseRequestManagement::getId, id).set(ErpPurchaseRequestManagement::getDocStatus, 1).set(ErpPurchaseRequestManagement::getAuditStatus, 1);
        int update = erpPurchaseRequestManagementMapper.update(null, lambdaUpdateWrapper);
        //可以进行审核
        Map<String, Integer> objectObjectMap = new HashMap<>();
        if (update > 0) {

            //审核状态为可审核 审核按钮为可审核
            objectObjectMap.put("审核按钮状态", 1);
            objectObjectMap.put("提交成功？", 1);
            return objectObjectMap;
        } else {
            objectObjectMap.put("提交失败", 0);
            return objectObjectMap;
        }


    }

    @Override
    public Map<String, String> end(List<Integer> ids, String reason) {
        Map<String, String> endMap = new HashMap<>();
        Set<Integer> resultKeys = new HashSet<>();
        ForceTerminationLog forceTerminationLog = new ForceTerminationLog();
        //先获取每个id的原状态
        Map<Integer, Integer> one = new HashMap<>();

        for (Integer id : ids) {
            LambdaQueryWrapper<ErpPurchaseRequestManagement> queryWrapper = Wrappers.lambdaQuery();
            LambdaQueryWrapper<ErpPurchaseRequestManagement> eq = queryWrapper.eq(ErpPurchaseRequestManagement::getId, id);  // 指定要查询的字段
            ErpPurchaseRequestManagement erpPurchaseRequestManagement = erpPurchaseRequestManagementMapper.selectOne(eq);

            int docStatus1 = erpPurchaseRequestManagement.getDocStatus();
            int id1 = erpPurchaseRequestManagement.getId();
            one.put(id1, docStatus1);
        }
        List<Integer> list = new ArrayList<>();
        list.add(0);
        list.add(1);
        list.add(2);


        Collection<Integer> values = one.values();
        List<Integer> valueList = new ArrayList<>(values);
        //符合强制关闭的值
        List<Integer> commonElements = valueList.stream()
                .filter(list::contains)
                .collect(Collectors.toList());

//                     // 收集符合处理状态的主键id

//                    记录强制终止的记录
        resultKeys = commonElements.stream()
                .flatMap(value -> one.entrySet().stream()
                        .filter(entry -> Objects.equals(entry.getValue(), value))
                        .map(Map.Entry::getKey))
                .collect(Collectors.toSet());
        System.out.println("resultKeys = " + resultKeys);

        for (Integer commonElement : commonElements) {
            //终止前的订单状态
            forceTerminationLog.setOriginalStatus(commonElement);
            //记录终止原因吗
            forceTerminationLog.setTerminationReason(reason);
            LocalDateTime currentTime = LocalDateTime.now();
            forceTerminationLog.setOperationTime(currentTime);
            forceTerminationLog.setProcessType("请购单");
//                    2代表请购单的所有强制终止记录
            forceTerminationLog.setProcessInstanceId(2);
//                    后面要修改为角色的名字
            forceTerminationLog.setOperator("超级管理员");
            //将记录加入到强制终止记录表中


            try {

                switch (forceTerminationMapper.insert(forceTerminationLog)) {
                    case 1:
                        endMap.put("强制终止是否成功", "终止成功");
                    case 0:
                        endMap.put("强制终止是否成功", "失败请重试");

                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        for (Integer i : resultKeys) {
            LambdaUpdateWrapper<ErpPurchaseRequestManagement> end = new LambdaUpdateWrapper<>();
            end.eq(ErpPurchaseRequestManagement::getId, i).set(ErpPurchaseRequestManagement::getDocStatus, 3).set(ErpPurchaseRequestManagement::getAuditStatus, 5);
            erpPurchaseRequestManagementMapper.update(null, end);

        }

        return endMap;
    }

    /*拒绝审核*/
    @Override
    public int rejectaudit(int id) {

        LambdaUpdateWrapper<ErpPurchaseRequestManagement> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(ErpPurchaseRequestManagement::getId, id).set(ErpPurchaseRequestManagement::getAuditStatus, 0).set(ErpPurchaseRequestManagement::getDocStatus, 0);
        int update = erpPurchaseRequestManagementMapper.update(null, lambdaUpdateWrapper);
        if (update > 0) {
            return update;
        }
        return 0;
    }

    @Override
    public List<PurchaseDetailBom> PurchaseDetail(int id) {
        // 创建分页对象
         List<PurchaseDetailBom> purchaseDetailBomslist = erpPurchaseRequestPendingDetailMapper.selectPurchaseDetailVO(id);
        return purchaseDetailBomslist;

    }

    @Override
    public List<PurchaseDetailBom> selectmaterials() {
        List<PurchaseDetailBom> purchaseDetailBoms = erpPurchaseRequestPendingDetailMapper.selectmaterials();
        return purchaseDetailBoms;

    }

    @Override
    public List<PurchaseDetailBom> PurchaseDetailId(int id) {
        List<PurchaseDetailBom> purchaseDetailBoms = erpPurchaseRequestPendingDetailMapper.PurchaseDetailId(id);
        return purchaseDetailBoms;
    }

    @Override
    public int deleteDetailId(int id, int wid) {
        int purchaseDetailBoms = erpPurchaseRequestPendingDetailMapper.deleteDetailId(id, wid);
        return purchaseDetailBoms;
    }

    @Override
    public int updatesw(ErpPurchaseRequestManagement erpPurchaseRequestManagement) {
        LambdaUpdateWrapper<ErpPurchaseRequestManagement> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(ErpPurchaseRequestManagement::getId, erpPurchaseRequestManagement.getId());
        int rows = erpPurchaseRequestManagementMapper.update(erpPurchaseRequestManagement, lambdaUpdateWrapper);
        return rows;

    }

    @Override
    public List<ApprovalRecord> jilu(Integer id) {
QueryWrapper<ApprovalRecord> wrapper=new QueryWrapper<>();
        wrapper.eq("ji_id", id); // 直接使用数据库列名
        List<ApprovalRecord> approvalRecords = approvalRecordMapper.selectList(wrapper);
        System.err.println(approvalRecords);
        return approvalRecords;

    }

    public List<ErpPurchaseRequestManagement> selectAllinsertOrder() {
       LambdaQueryWrapper<ErpPurchaseRequestManagement> queryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<ErpPurchaseRequestManagement> eq = queryWrapper.eq(ErpPurchaseRequestManagement::getAuditStatus, 2);
        List<ErpPurchaseRequestManagement> list = this.list(eq);

        return list;

    }

    }





